# Autosub Db.py - http://code.google.com/p/auto-sub/
#
# The Autosub scanDisk module
#

import logging
import os
import re

# Autosub specific modules
import autosub
import autosub.Helpers
import autosub.Db
# Settings
log = logging.getLogger('thelogger')


class scanDisk():
    """
    Scan the specified path for episodes without Dutch or (if wanted) English subtitles.
    If found add these Dutch or English subtitles to the WANTEDQUEUE.
    """
    def run(self):
        log.info("scanDir: Starting round of local disk checking")
        if autosub.WANTEDQUEUELOCK == True:
            log.debug("scanDir: Exiting, another threat is using the queues")
            return False
        else:
            autosub.WANTEDQUEUELOCK = True
        
        dbconnection = autosub.Db.dbCon()
        databasecursor = dbconnection.runQuery('select bierdopje_id, LocationOnDisk from tv_shows', ())
        paths = []
        for row in databasecursor:
            dictitem = {}
            dictitem['path'] = row[1]
            dictitem['showid'] = int(row[0])
            paths.append(dictitem)
        
        if not len (paths) > 0:
            log.warning("scanDisk: No shows added yet")
            log.info("scanDir: Finished round of local disk checking")
            autosub.WANTEDQUEUELOCK = False
            autosub.WIPSTATUS.runnow = True
            return True
        
        for dict in paths:
            for dirname, dirnames, filenames in os.walk(dict['path']):
                for filename in filenames:
                    splitname = filename.split(".")
                    ext = splitname[len(splitname) - 1]
    
                    if ext in ('avi', 'mkv', 'wmv', 'ts', 'mp4'):
                        if re.search('sample', filename): continue
    
                        # What subtitle files should we expect?
                        if (autosub.SUBNL != ""):
                            srtfile = os.path.join(filename[:-4] + "." + autosub.SUBNL + ".srt")
                        else:
                            srtfile = os.path.join(filename[:-4] + ".srt")
                            
                        srtfileeng = os.path.join(filename[:-4] + "." + autosub.SUBENG + ".srt")
    
                        if not os.path.exists(os.path.join(dirname, srtfile)) or (not os.path.exists(os.path.join(dirname, srtfileeng)) and autosub.DOWNLOADENG):
                            log.debug("scanDir: File %s is missing a subtitle" % filename)
                            lang = []
                            filenameResults = autosub.Helpers.ProcessFileName(os.path.splitext(filename)[0], os.path.splitext(filename)[1])
                            if 'title' in filenameResults.keys():
                                if 'season' in filenameResults.keys():
                                    if 'episode' in filenameResults.keys():
                                        title = filenameResults['title']
                                        season = filenameResults['season']
                                        episode = filenameResults['episode']
                                        
                                        showid = autosub.Helpers.GetShowId(title)
                                        if not showid == dict['showid'] or showid == -1:
                                            log.debug("scanDir: Either the showid does not match or could not determine showid. Show ID is %d and trying to match it with %d" %(showid, dict['showid']))
                                            continue
                                        
                                        if autosub.Helpers.SkipShow(title, season, episode) == True:
                                            log.debug("scanDir: SkipShow returned True")
                                            log.info("scanDir: Skipping %s - Season %s Episode %s" % (title, season, episode))
                                            continue
                                        log.info("scanDir: Dutch subtitle wanted for %s and added to wantedQueue" % filename)
                                        filenameResults['originalFileLocationOnDisk'] = os.path.join(dirname, filename)
                                        
                                        if not os.path.exists(os.path.join(dirname, srtfile)):
                                            lang.append('nl')
                                        if not os.path.exists(os.path.join(dirname, srtfileeng)) and (autosub.FALLBACKTOENG or autosub.DOWNLOADENG):
                                            lang.append('en')
                                        
                                        filenameResults['lang'] = lang
                                        autosub.WANTEDQUEUE.append(filenameResults)
                                        
                                    else:
                                        log.error("scanDir: Could not process the filename properly filename: %s" % filename)
                                        continue
                                else:
                                    log.error("scanDir: Could not process the filename properly filename: %s" % filename)
                                    continue
                            else:
                                log.error("scanDir: Could not process the filename properly filename: %s" % filename)
                                continue
                    
        log.debug("scanDir: Finished round of local disk checking")
        autosub.WANTEDQUEUELOCK = False
        autosub.WIPSTATUS.runnow = True
        return True

def processPath(path):
    """
    Used by the webinterface to determine a show name.

    Keyword arguments:
    path -- a local file system path. str
    """
    
    l = []
    for dirname, dirnames, filenames in os.walk(path):
        for filename in filenames:
            splitname = filename.split(".")
            ext = splitname[len(splitname) - 1]

            if ext in ('avi', 'mkv', 'wmv', 'ts', 'mp4'):
                if re.search('sample', filename): continue
                filenameResults = autosub.Helpers.ProcessFileName(os.path.splitext(filename)[0], os.path.splitext(filename)[1])
                if 'title' in filenameResults.keys():
                    if 'season' in filenameResults.keys():
                        if 'episode' in filenameResults.keys():

                            l.append(filenameResults['title'])
                            
                        else:
                            log.error("scanDir: Could not process the filename properly filename: %s" % filename)
                            continue
                    else:
                        log.error("scanDir: Could not process the filename properly filename: %s" % filename)
                        continue
                else:
                    log.error("scanDir: Could not process the filename properly filename: %s" % filename)
                    continue
    return l

def scanEpisodes(path, showid):
    """
    Call this function with a local showid, not a bierdopje id.
    """
    for dirname, dirnames, filenames in os.walk(path):
        for filename in filenames:
            splitname = filename.split(".")
            ext = splitname[len(splitname) - 1]

            if ext in ('avi', 'mkv', 'wmv', 'ts', 'mp4'):
                if re.search('sample', filename): continue
                filenameResults = autosub.Helpers.ProcessFileName(os.path.splitext(filename)[0], os.path.splitext(filename)[1])
                if 'title' in filenameResults.keys():
                    if 'season' in filenameResults.keys():
                        if 'episode' in filenameResults.keys():
                            
                            title = filenameResults['title']
                            showidtitle = autosub.Helpers.GetShowId(title)
                            localshowid = autosub.Helpers.getLocalShowId(showidtitle, path=path)
                            episode = filenameResults['episode']
                            season = filenameResults['season']
                            if 'source' in filenameResults.keys():
                                source = filenameResults['source']
                            else:
                                source = None
                            
                            if 'quality' in filenameResults.keys():
                                quality = filenameResults['quality']
                            else:
                                quality = None
                                
                            if 'releasegrp' in filenameResults.keys():
                                releasegrp = filenameResults['releasegrp']
                            else:
                                releasegrp = None
                            nlwanted = None
                            enwanted = None
                            downloadedsubnl = None
                            downloadedsuben = None
                            localvideofile = filename
                            nlsrtfile = None
                            ensrtfile = None
                            airdate = None
                            
                            lang = []
                            if (autosub.SUBNL != ""):
                                nlsrtfile = os.path.join(filename[:-4] + "." + autosub.SUBNL + ".srt")
                            else:
                                nlsrtfile = os.path.join(filename[:-4] + ".srt")
                            
                            ensrtfile = os.path.join(filename[:-4] + "." + autosub.SUBENG + ".srt")
                            
                            if not showid == localshowid or showid == -1:
                                log.debug("scanEpisodes: Either the showid does not match or could not determine showid. Show ID is %d and trying to match it with %d" %(showid, localshowid))
                                continue
                            else:
                                langs = autosub.Helpers.getWantedLang(showid)
                                nlwanted = langs[0]
                                enwanted = langs[1]
                                
                                if nlwanted == 1:
                                    if os.path.exists(os.path.join(dirname, nlsrtfile)):
                                        nlwanted = 0
                                
                                if enwanted == 1:
                                    if os.path.exists(os.path.join(dirname, ensrtfile)):
                                        enwanted = 0
                                
                                if enwanted == 4:
                                    if nlwanted == 0:
                                        enwanted = 0
                                
                                nlsrtfile = os.path.join(dirname, nlsrtfile)
                                ensrtfile = os.path.join(dirname, ensrtfile)
                                localvideofile = os.path.join(dirname, localvideofile)
                                
                                dbconnection = autosub.Db.dbCon()
                                dbconnection.runQuery('insert into episodes values (NULL,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',[
                                                                        localshowid,
                                                                        episode,
                                                                        season,
                                                                        source,
                                                                        quality,
                                                                        releasegrp,
                                                                        nlwanted,
                                                                        enwanted,
                                                                        downloadedsubnl,
                                                                        downloadedsuben,
                                                                        localvideofile,
                                                                        nlsrtfile,
                                                                        ensrtfile,
                                                                        airdate])
                                    
                        else:
                            log.error("scanDir: Could not process the filename properly filename: %s" % filename)
                            continue
                    else:
                        log.error("scanDir: Could not process the filename properly filename: %s" % filename)
                        continue
                else:
                    log.error("scanDir: Could not process the filename properly filename: %s" % filename)
                    continue